package com.local.web.controller;

import com.local.common.constants.BusinessException;
import com.local.common.constants.ExceptionCodeEnum;
import com.local.common.constants.SystemException;
import com.local.common.util.ResultUtil;
import com.local.web.util.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@RestControllerAdvice
@Slf4j
public class ExceptionAdvice {

    @ExceptionHandler(Exception.class)
    public Object doException(Exception e, HttpServletRequest request){
        ResultUtil result;
        if (e instanceof BusinessException) {
            BusinessException exception = (BusinessException) e;
            result = new ResultUtil(exception.getCode(), exception.getMessage());
        } else if (e instanceof SystemException) {
            //系统异常
            //记录日志
            log.error(e.getMessage(), e);

            SystemException exception = (SystemException) e;
            result = new ResultUtil(exception.getCode(), exception.getMessage());
        } else {
            //其他异常
            //记录日志
            log.error(e.getMessage(), e);

            result = new ResultUtil(ExceptionCodeEnum.SYSTEM_EXCEPTION.getCode(), e.getMessage());
        }

        //如果是ajax请求，则返回json
        if (CommonUtil.isAjaxRequest(request)) {
            return result;
        }

        //如果是页面请求，则显示错误页面
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("message", e.getMessage());
        modelAndView.addObject("url", request.getRequestURL());
        modelAndView.addObject("stackTrace", e.getStackTrace());
        modelAndView.addObject("author", "管理员");
        modelAndView.addObject("ltd", "平台");
        modelAndView.setViewName("error/error");
        return modelAndView;
    }

}
